package com.almond.mq.receiver;

import com.almond.mq.model.OrderNotifyMQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.messaging.handler.annotation.Header;
import com.rabbitmq.client.Channel;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * rabbitMQ消息接收器：仅在vender=rabbitMQ时 && 项目实现IMQReceiver接口时 进行实例化
 * 业务：  支付订单商户通知
 *
 * @author tnar
 */
@Slf4j
@Component
@ConditionalOnBean(OrderNotifyMQ.IMQReceiver.class)
public class PayOrderMchNotifyRabbitMQReceiver implements IMQMsgReceiver {

    @Autowired
    private OrderNotifyMQ.IMQReceiver mqReceiver;

    /**
     * 接收 【 queue 】 类型的消息
     **/
    @Override
    @RabbitListener(queues = OrderNotifyMQ.MQ_NAME)
    public void receiveMsg(String msg, Channel channel,
                           @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        try {
            log.info("Received: " + msg);
            mqReceiver.receive(OrderNotifyMQ.parse(msg));
            // 业务处理...
            channel.basicAck(tag, false); // 确认消息
        } catch (Exception e) {
            channel.basicNack(tag, false, true); // 拒绝消息并重新入队
            // 或者 channel.basicReject(tag, false); // 拒绝消息不重新入队
        }
    }

}
